<template>
  <div>
    <el-col :span="24" class="toolbar" style="padding: 10px">
      <div class="d-flex a-center j-sb">
        <el-form :inline="true" :model="filters">
          <el-form-item>
            <el-input v-model="filters.typeName" placeholder="输入角色名称"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getFilterData">查询</el-button>
            <el-button type="primary" @click="getAllData">新增</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-col>
    <template>
      <el-table
        :data="dataList"
        ref="multipleTable"
        highlight-current-row
        style="width: 100%;"
        stripe
        border
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
      >
        <el-table-column type="index" :index='indexMethods' label="ID" min-width="10" align="center"></el-table-column>
        <el-table-column prop="descn" label="角色名称" min-width="12" align="center"></el-table-column>
        <el-table-column prop="name" label="英文名称" min-width="12" align="center"></el-table-column>
        <el-table-column prop="url" label="默认跳转路径" min-width="12" align="center"></el-table-column>
        <el-table-column label="操作" min-width="20" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="updateData(scope.row)">修改角色信息</el-button>
            <el-button size="mini" type="primary" @click="amendData(scope.row)">角色权限</el-button>
            <el-button
              size="mini"
              type="danger"
              style="margin-left:2vw"
              @click="deleteData(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <el-pagination
      style="float:right;padding:5px;margin-top:10px;"
      background
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-size="10"
      layout="total, prev, pager, next"
      :total="pageTotal"
    ></el-pagination>
    <el-dialog :visible.sync="dialogVisible" width="30%" center :show-close="false">
      <div class="head">
        <div class="title">
          {{dialogTitle}}
          <div class="close" @click="close">X</div>
        </div>
      </div>
      <div class="tree">
        <el-form
          v-if="isInsert"
          :inline="true"
          label-position="right"
            label-width="140px"
          :model="formData"
          class="demo-form-inline"
          :rules="rules"
          ref="roleForm"
        >
          <el-form-item label="角色名称：" prop="descn">
            <el-input v-model="formData.descn"></el-input>
          </el-form-item>
          <el-form-item label="英文名称：" prop="name">
            <el-input v-model="formData.name"></el-input>
          </el-form-item>
          <el-form-item label="默认跳转路径：" prop="url">
            <el-input v-model="formData.url"></el-input>
          </el-form-item>
        </el-form>
        <el-tree
          v-else-if="!isInsert"
          ref="rightsTree"
          :data="menusList"
          show-checkbox
          node-key="id"
          :props="defaultProps"
          :default-expanded-keys="checkedList"
          :default-checked-keys="checkedList"
        ></el-tree>
      </div>
      <div slot="footer" class="text-center">
        <el-button style="margin-right:20px" @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisibleTrue">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      filters: { typeName: "" },
      dataList: [],
      currentPage: 1,
      pageTotal: null,
      dialogVisible: false,
      menusList: [], //权限集合
      defaultProps: {
        children: "childLs",
        label: "name"
      },
      dialogTitle: "", //弹窗title
      checkedList: [], //默认选择的权限
      list: [],
      roleId: null,
      roleName: "",
      isInsert: false,
      formData: {},
      rules: {
        descn: [{ required: true, message: "请填写角色名称", trigger: "blur" }],
        name: [{ required: true, message: "请填写英文名称", trigger: "blur" }],
        url: [
          { required: true, message: "请填写默认跳转路径", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getRoles();
    this.getAllMenus();
  },
  methods: {
    //分页序号连续
    indexMethods(index){
      return (index+1)+((this.currentPage-1)*10)
    },
    getRoles() {
      this.post(
        "/operation/getRoles",
        { pageSize: 10, pageNum: this.currentPage ,descn:this.filters.typeName},
        res => {
          if (res.code == 200) {
            this.dataList = res.data.list;
            this.pageTotal = res.data.total;
          }
        },
        false
      );
    },
    //删除
    deleteData(row) {
      this.$confirm("确认删除？")
        .then(_ => {
          // this.post(
          //   "/medicalAdministration/delete",
          //   { id: row.id },
          //   res => {
          //     if (res.code == 200) {
          //       this.selectMedicalPage();
          //       this.$message.success("删除成功");
          //     }
          //   },
          //   false
          // );
        })
        .catch(_ => {});
    },
    //查询
    getFilterData() {
      this.getRoles()
    },
    //新增
    getAllData() {
      this.dialogVisible = true;
      this.isInsert = true;
      this.dialogTitle = "新增角色";
    },
    handleCurrentChange(num) {
      this.currentPage = num;
      this.getRoles();
    },
    forMap(item) {
      console.log(item);
      item.map(e => {
        this.list.push(e.id);
        if (e.childLs) {
          this.forMap(e);
        } else {
          return false;
        }
      });
    },
    //修改角色信息
    updateData(row){
      this.dialogVisible = true;
      this.isInsert = true;
      this.dialogTitle = "修改角色信息";
      this.formData=row
      console.log(row)
    },
    //角色权限页面
    amendData(row) {
      this.isInsert = false;
      this.roleId = row.id;
      this.roleName = row.name;
      this.list = [];
      this.checkedList = [];
      this.dialogVisible = true;
      this.dialogTitle = `给"${row.descn}"分配资源`;
      this.post(
        "/operation/getAllMenus",
        { roleId: row.id },
        res => {
          if (res.code == 200) {
            console.log(res.data)
            res.data.map(e => {
              if (e.childLs) {
                this.forMap(e.childLs);
              } else {
                return false;
              }
            });
            this.checkedList = this.list;
            console.log(this.checkedList)
            this.$nextTick(() => {
              this.$refs["rightsTree"].setCheckedKeys(this.checkedList);
            });
          }
        },
        false
      );
    },
    //获取所有权限
    getAllMenus() {
      this.post(
        "/operation/getAllMenus",
        {},
        res => {
          if (res.code == 200) {
            this.menusList = res.data;
          }
        },
        false
      );
    },
    close() {
      this.dialogVisible = false;
    },
    //保存分配的权限
    dialogVisibleTrue() {
      if (this.dialogTitle=='新增角色') {
        this.$refs['roleForm'].validate(valid => {
          if (valid) {
            this.post(
              "/operation/insertRole",
              this.formData,
              res => {
                this.dialogVisible = false;
                this.getRoles();
                this.$message.success("新增成功");
                this.formData={}
              },
              false
            );
          }
        });
      }else if(this.dialogTitle=='修改角色信息'){
        this.$refs['roleForm'].validate(valid => {
          if (valid) {
            this.post(
              "/operation/updateRole",
              this.formData,
              res => {
                this.dialogVisible = false;
                this.getRoles();
                this.$message.success("修改成功");
                this.formData={}
              },
              false
            );
          }
        });
      }else {
        let list = [];
        this.$refs["rightsTree"].getCheckedNodes().forEach(e => {
          list.push(e.id);
        });
        // var temp = [];
        // for(var i = 0; i < list.length; i++) {
        //     //如果当前数组的第i项在当前数组中第一次出现的位置是i，才存入数组；否则代表是重复的
        //     if(list.indexOf(list[i]) == i){
        //         temp.push(list[i])
        //     }
        // }
        let list1 = this.$refs["rightsTree"].getHalfCheckedKeys()
        this.post(
          "/operation/updateRoleMenus",
          {
            roleId: this.roleId,
            menuIds: list.concat(list1),
            roleName: this.roleName
          },
          res => {
            if (res.code == 200) {
              this.dialogVisible = false;
              this.$message.success("修改成功");
            }
          },
          false
        );
      }
    }
  }
};
</script>

<style lang="less" scoped>
/deep/.el-dialog__header {
  padding: 0;
}
/deep/.el-dialog--center .el-dialog__body {
  padding: 0;
}
.tree {
  margin: 20px;
  border: 1px solid #eee;
  padding: 10px;
  height: 250px;
  overflow-y: scroll;
  &::-webkit-scrollbar {
    width: 1px;
  }
  /deep/.el-tree {
    .el-tree-node {
      margin-bottom: 10px;
    }
  }
  /deep/.el-form-item{
    width: 100%;
}
}
.head {
  .title {
    height: 60px;
    background-color: #0882f4;
    font-size: 20px;
    text-align: center;
    line-height: 60px;
    color: #fff;
    position: relative;
    .close {
      position: absolute;
      top: 0;
      right: 15px;
      font-size: 20px;
      color: #fff;
      cursor: pointer;
    }
  }
}
</style>